import TextWidget from './text-widget.js'
import {WIDGET_TYPE} from './widget-const.js';

const _template = Object.freeze({
    path: "./code.jpg",
    align: 0,
    caption: "caption",
});

export default class ImageWidget extends TextWidget {
    constructor(sectionData, dispatcher) {
        super(sectionData, dispatcher);
        try {
            this._data = JSON.stringify(this._sectionData.content ?? _template, null, 4);
        } catch (e) {
            this._data = JSON.stringify(_template, null, 4);
            console.error(e);
        }
    }

    get sectionData() {
        this._sectionData.type = WIDGET_TYPE.IMAGE;
        this._sectionData.content = JSON.parse(this._data);
        return this._sectionData;
    }
    get textareaText() {return this._data;}
    set textareaText(value) {this._data = value;}
    get language() {return 'json';}
    Init() {
        super.Init();
        this._editContainerElem.setAttribute('data-language', 'image');
        return this;
    }

    _UpdateView() {
        try {
            const _data = JSON.parse(this._data);
            let _align;
            if (_data.align < 0) _align = "text-start";
            else if (_data.align > 0) _align = "text-end";
            else _align = "text-center";

            this._viewContainerElem.innerHTML = `
<div class="${_align}">
  <figure class="figure">
    <img src="${_data.path}" class="figure-img img-fluid rounded" alt="...">
    <figcaption class="figure-caption text-center">${_data.caption}</figcaption>
  </figure>
</div>
`;

        } catch(e) {
            this._viewContainerElem.innerText = e.message;
            console.log(e.stack);
        }
    }
};

